package com.jiangruan.javaproject.request.service;

import com.alibaba.fastjson.JSONObject;
import com.jiangruan.javaproject.Constants;
import com.jiangruan.javaproject.entity.Result;
import com.jiangruan.javaproject.entity.Result_count;
import com.jiangruan.javaproject.request.HttpUtils;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:liufukai
 * @email:1324963242@qq.com
 * @desc:该类用于实现通过rpc调用比特币客户端的getblockcount功能
 * @datatime:2021/12/2821:43
 */
public class GetblockcountService {
    public int getblockcount(){
        String au=Constants.BITCOIN_RPC_USER+":"+Constants.BITCOIN_RPC_PWD;

        Base64.Encoder encoder=Base64.getEncoder();
        String auBase64=encoder.encodeToString(au.getBytes());

        //准备请求头信息
        Map<String,String> head=new HashMap<>();
        head.put("Content-Type","application/json");
        head.put("Authorization", "Basic " +auBase64);
        //准备要发送的rpc数据
        Map<String,Object> body1=new HashMap<>();
        body1.put("id",1002);
        body1.put("method","getblockcount");
        body1.put("params",null);
        body1.put("json_rpc","2.0");
        //将map转换成byte[]
        byte[] bodyBytes = JSONObject.toJSONBytes(body1);
        //格式：{"id"，"1001","result":xxx,"error":null}
        String result= HttpUtils.post(Constants.BITCOIN_RPC_URL,head,bodyBytes);
        //反序列化
        Result_count result1 = JSONObject.parseObject(result, Result_count.class);
        System.out.println(result1.result);

       return result1.result;
    }
}
